package cn.itsource.smartcampus.controller;

import cn.itsource.smartcampus.util.AjaxResult;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CookieController {
    /**
     * 新增
     * @param response
     * @return
     */
    @GetMapping("/cook")
    public AjaxResult<Object> testCookie(HttpServletResponse response) {
        // 1.创建一个Cookie对象
        Cookie cookie = new Cookie("name", "Tom");
        // 2.设置到响应对象中带给浏览器
        response.addCookie(cookie);
        return AjaxResult.ok("访问成功");
    }

    /**
     * 查询
     * @param request
     * @return
     */
    @GetMapping("/cook1")
    public AjaxResult<Void> testCookie(HttpServletRequest request) {
        // 1.从请求对象中获取到所有的cookie
        Cookie[] cookies = request.getCookies();
        // 2.遍历cookie数组
        for (Cookie cookie : cookies) {
            // 3.取值并打印
            System.out.println(cookie.getName() + "--" + cookie.getValue());
        }
        return AjaxResult.ok("访问成功！");
    }

    /**
     * 删除
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/cook2")
    public AjaxResult<Void> testCookie(HttpServletRequest request, HttpServletResponse response) {
        // 1.从请求对象中获取到所有的cookie
        Cookie[] cookies = request.getCookies();
        // 2.遍历cookie数组
        for (Cookie cookie : cookies) {
            // 3.判断是否是我们要操作的cookie
            if ("name".equals(cookie.getName())){
                // 4.如果是设置cookie剩余存活时间为0
                cookie.setMaxAge(0);
                // 5.必须要响应给浏览器才算设置成功
                response.addCookie(cookie);
            }
        }
        return AjaxResult.ok("访问成功！");
    }
}
